/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.action;

import apus.authorisation.UserAuthorisation;
import apus.entity.Account;
import apus.entity.User;
import apus.persistence.*;
import apus.persistence.jdbc.DataBaseStatistics;
import apus.services.ServiceLocator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author 21vek
 */
public class ViewMainPageAction implements Action{

    @Override
    public String getName() {
        return "main.view";
    }

    @Override
    public ActionResult execute(HttpServletRequest request, HttpServletResponse response) {
        UserAuthorisation ua = (UserAuthorisation) request.getSession().getAttribute("userAuth");
        UserAuthorisation.Role role = ua.getRole();
        
        if (role.equals(UserAuthorisation.Role.ADMIN)) {
            request.setAttribute("statistics", DataBaseStatistics.getStatistics());
            return ActionResult.forward("/WEB-INF/View/mainAdmin.jsp");
        }
        
        if (role.equals(UserAuthorisation.Role.CASHIER)) {
            request.setAttribute("phoneNumberList", (ServiceLocator.getService(PhoneNumberDAO.class)).findAll());
            return ActionResult.forward("/WEB-INF/View/mainCashier.jsp");
        }
        
        if (role.equals(UserAuthorisation.Role.USER)) {
            UserDAO udao=ServiceLocator.getService(UserDAO.class);
            User user=udao.findByLogin(ua.getLogin());
            int id=user.getSubscriber().getId();
            if (user.getSubscriber().getSubscriberType().equals("person")){
            request.setAttribute("person", ServiceLocator.getService(PersonDAO.class).read(user.getSubscriber().getId()));
            } else{
                request.setAttribute("organization", ServiceLocator.getService(OrganizationDAO.class).read(user.getSubscriber().getId()));
            }
            AccountDAO adao=ServiceLocator.getService(AccountDAO.class);
            List<Account> accList=adao.readBySubscriber(id);
            for (Account acc:accList){
                if(!acc.isPaid()){
                    request.setAttribute("not_paid",true);
                    break;
                }
            }
            return ActionResult.forward("/WEB-INF/View/mainUser.jsp");
        }
        
        return ActionResult.forward("/WEB-INF/View/loginPage.jsp");
        
    }
    
}
